<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 消息提示 -->
    <el-alert
      title="注意：只允许设置三级分类的参数"
      type="warning"
      show-icon
      :closable="false"
    >
    </el-alert>
    <!-- 选择商品分类 -->
    <el-row class="cate_opt">
      <el-col>
        <span>选择商品分类：</span>
        <!-- 级联选择器 -->
        <el-cascader
          clearable
          collapse-tags
          v-model="selectedCates"
          :options="setCateList"
          :props="{
            checkStrictly: true,
            expandTrigger: 'hover',
            value: 'cat_id',
            label: 'cat_name',
            children: 'children',
          }"
          @change="handleChange"
        ></el-cascader>
      </el-col>
    </el-row>
    <!-- tabs栏 -->
    <el-row>
      <el-col>
        <!-- 动态参数tab -->
        <el-tabs v-model="activeName" @tab-click="handleChange">
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              size="mini"
              :disabled="disableBtn"
              @click="showManyDialog"
            >
              添加动态参数</el-button
            >
            <!-- 动态参数的表格 -->
            <el-table :data="manyData" style="width: 100%" border stripe>
              <!-- 展开列 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="item.id"
                    closable
                    @close="delTag(scope.row, index)"
                    >{{ item }}
                  </el-tag>
                  <!--  -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.addTaginputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="addTag(scope.row)"
                    @blur="addTag(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="ShowEditDialog(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="delMany(scope.row.attr_id)"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 配置管理的tab -->
          <el-tab-pane label="配置管理" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="disableBtn"
              @click="showManyDialog"
            >
              添加静态属性</el-button
            >
            <!-- 静态属性表格 -->
            <el-table :data="onlyData" style="width: 100%" border stripe>
              <!-- 展开列 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="item.id"
                    closable
                    @close="delTag(scope.row, index)"
                    >{{ item }}
                  </el-tag>
                  <!--  -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.addTaginputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="addTag(scope.row)"
                    @blur="addTag(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    size="mini"
                    @click="
                      ShowEditDialog(scope.row.attr_name, scope.row.attr_id)
                    "
                    >编辑</el-button
                  ><el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="delMany(scope.row.attr_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <!-- 添加分类动态属性对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态属性' : '添加静态属性'"
      :visible.sync="isShowManyDialog"
      width="50%"
    >
      <el-form
        ref="form"
        :model="addManyForm"
        :rules="addManyFormRules"
        label-width="80px"
      >
        <!-- 表单内容输入区 -->
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowManyDialog = false">取 消</el-button>
        <el-button type="primary" @click="doAddMany">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑修改对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '修改动态属性' : '修改静态属性'"
      :visible.sync="isShowEditDialog"
      width="50%"
    >
      <el-form
        ref="form"
        :model="editManyForm"
        :rules="editManyFormRules"
        label-width="80px"
      >
        <!-- 表单内容输入区 -->
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="editMany">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 计算属性
  computed: {
    // 下拉框
    disableBtn () {
      return this.selectedCates.length !== 3
    }
  },
  created () {
    //  分类商品列表
    this.getCateList()
  },
  data () {
    return {
      //  添加分类 下拉框数组
      setCateList: [],
      // 添加分类 选中的 父类id
      selectedCates: [],
      // tab栏选中数据
      activeName: 'many',
      // 动态参数的数据
      manyData: [],
      // 静态属性的数据
      onlyData: [],
      // 显示 添加分类的弹出对话框
      isShowManyDialog: false,
      // 动态参数表单数据
      addManyForm: {
        attr_name: '',
        attr_sel: 0 // this.activeName 取不到 在方法里加
      },
      // 动态参数表单 验证规则
      addManyFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur' }
        ]
      },
      //
      isShowEditDialog: false,

      // 编辑修改提交参数
      editManyForm: {
        attr_name: '',
        attr_sel: 0 // this.activeName 取不到 在方法里加
      },
      //
      editManyFormRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 9, message: '长度在 1 到 9 个字符', trigger: 'blur' }
        ]
      },
      // 添加tag 数组
      addTaginputValue: '',
      //
      inputVisible: false
    }
  },
  methods: {
    //  获取分类列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 保存列表数组
      this.setCateList = res.data
    },
    // 监听分类下拉框 改变事件(tab栏切换)
    async handleChange () {
      // 如果选中的类别数组元素少于三个 就清空选中项
      if (this.selectedCates.length < 3) {
        this.selectedCates.length = 0
        // 清空下拉框绑定的数据数组
        this.manyData = []
        this.onlyData = []
        return
      }
      const cateId = this.selectedCates[2] // 三级菜单id
      // 请求接口
      const { data: res } = await this.$http.get(
        `categories/${cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // 修改返回的数据 将字符串以逗号分隔改成数组(展开列中使用渲染tag)
      res.data.forEach((ele) => {
        if (ele.attr_vals) {
          ele.attr_vals = ele.attr_vals.split(',')
        } else ele.attr_vals = []
        // 为每一个数据对象 添加inputVisible 属性控制当前行显示标签/input框
        ele.inputVisible = false
        // 为每一个数据对象 添加addInputVisible 分开保存输入的文本值
        ele.addTaginputValue = ''
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 判断点击的是哪个tab栏 保存对应的数据数组
      if (this.activeName === 'many') this.manyData = res.data
      this.onlyData = res.data
    },
    // 显示动态参数
    showManyDialog () {
      this.isShowManyDialog = true
    },
    // 添加分类
    async doAddMany () {
      this.addManyForm.attr_sel = this.activeName
      const cateId = this.selectedCates[2]
      // 发起请求
      const { data: res } = await this.$http.post(
        `categories/${cateId}/attributes`,
        this.addManyForm
      )
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 成功之后的操作
      this.isShowManyDialog = false
      this.addManyForm.attr_name = ''
      this.addManyForm.attr_sel = 'many'
      this.handleChange()
    },
    // 编辑显示对话框
    ShowEditDialog (rowData) {
      this.editManyForm.attr_name = rowData.attr_name
      this.editManyForm.attr_id = rowData.attr_id
      this.editManyForm.attr_vals = rowData.attr_vals.join(',')
      this.isShowEditDialog = true
    },
    // 点击编辑 修改事件
    async editMany () {
      this.editManyForm.attr_sel = this.activeName
      const cateId = this.selectedCates[2]
      const { data: res } = await this.$http.put(
        `categories/${cateId}/attributes/${this.editManyForm.attr_id}`,
        this.editManyForm
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 成功之后的操作 关闭对话框 清空(可选)
      this.isShowEditDialog = false
      this.editManyForm.attr_name = ''
      this.editManyForm.attr_sel = ''
      this.handleChange()
    },
    // 删除按钮事件
    delMany (attid) {
      this.$messageBox.confirm('尊敬的vip用户，您确定删除吗？', '系统提示', {
        confirmButtonText: '确定',
        callback: async (action) => {
          if (action === 'cancel') return
          const cateId = this.selectedCates[2]
          const { data: res } = await this.$http.delete(
            `categories/${cateId}/attributes/${attid}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          // 刷新页面
        }
      })
    },
    // 添加tag标签
    addTag (rowData) {
      // 检查数据
      if (rowData.addTaginputValue.trim().length === 0) {
        rowData.addTaginputValue = ''
        rowData.inputVisible = false
        return
      }
      // 检查通过后 显示新增tag 标签
      rowData.attr_vals.push(rowData.addTaginputValue.trim())
      rowData.addTaginputValue = ''
      // 调用新增tag方法
      this.updateTag(rowData)
      // 隐藏文本框
      rowData.inputVisible = false
    },
    // 更新tab (复用抽出来的)
    async updateTag (rowData) {
      // 将新增tag 提交到服务器保存
      const cateId = this.selectedCates[2]
      // 请求接口
      const { data: res } = await this.$http.put(
        `categories/${cateId}/attributes/${rowData.attr_id}`,
        {
          attr_name: rowData.attr_name,
          attr_sel: rowData.attr_sel,
          attr_vals: rowData.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    showInput (rowData) {
      rowData.inputVisible = true
      // 将显示的文本框 设置焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag
    delTag (rowData, index) {
      this.$messageBox.confirm('确定要删除吗？', '系统提示', {
        confirmButtonText: '确定',
        callback: (action) => {
          if (action === 'cancel') return
          rowData.attr_vals.splice(index, 1)
          // 异步请求
          this.updateTag(rowData)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin: 15px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
